package com.rajesh.messageservice.helper;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.OperationApplicationException;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;

import java.util.ArrayList;
import java.util.List;

/**
 * 手机联系人操作
 */
public class ContactsOperator {

    /**
     * 联系人数据载体
     * */
    public class Contact {
        public String Name;
        public String PhoneNumber;
        public String Email;
    }

    /**
     * 批量添加手机联系人
     *
     * @author Rajesh
     * @param context 程序上下文， 为了获取 ContentResolver
     * @param contacts 待添加的联系人列表
     * @throws RemoteException
     * @throws OperationApplicationException 当添加联系人失败的时候会抛出此异常
     * */
    public static void insertBatch(Context context, List<Contact> contacts) throws RemoteException, OperationApplicationException {
        ContentResolver resolver = context.getContentResolver();

        for (Contact contact: contacts) {
            ArrayList<ContentProviderOperation> operations = new ArrayList<>();
            //int rawContactInsertIndex = operations.size();
            //执行空值插入，使用 withValueBackReference 获取前面联系人的 id
            operations.add(ContentProviderOperation.newInsert(Uri.parse("content://com.android.contacts/raw_contacts"))
                    .withValue("_id", null)
                    .build());
            operations.add(ContentProviderOperation.newInsert(Uri.parse("content://com.android.contacts/data"))
                    .withValueBackReference("raw_contact_id", 0)
                    .withValue("mimetype", "vnd.android.cursor.item/name")
                    .withValue("data2", contact.Name)
                    .build());
            operations.add(ContentProviderOperation.newInsert(Uri.parse("content://com.android.contacts/data"))
                    .withValueBackReference("raw_contact_id", 0)
                    .withValue("mimetype", "vnd.android.cursor.item/phone_v2")
                    .withValue("data1", contact.PhoneNumber)
                    .withValue("data2", 2)
                    .build());
            operations.add(ContentProviderOperation.newInsert(Uri.parse("content://com.android.contacts/data"))
                    .withValueBackReference("raw_contact_id", 0)
                    .withValue("mimetype", "vnd.android.cursor.item/email_v2")
                    .withValue("data1", contact.Email)
                    .withValue("data2", 2)
                    .build());
            //批量添加联系人信息
            resolver.applyBatch(ContactsContract.AUTHORITY, operations);
        }
    }
}
